package cn.dengta.webapp.trade.config;

import java.util.Set;
import java.util.TreeMap;

import cn.dengta.common.context.Env;
import cn.dengta.common.util.HttpUtil;
import cn.dengta.common.web.Client;
import cn.dengta.webapp.base.entity.ChannelName;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Joiner;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import me.codeplayer.util.Encrypter;
import me.codeplayer.util.StringUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
@Getter
@Setter
@Slf4j
@ConfigurationProperties(prefix = "launch.inter")
public class LaunchInterAdConfig implements InitializingBean {

	private String baseUrl = "https://" + (Env.inProduction() ? "" : Env.CURRENT.value + "-") + "admonitor.dengtayiduiyi.com";
	public static final String register_url = "/behavior/register";
	public static final String pay_url = "/behavior/pay";
	private AppInfo android = new AppInfo("1927", "ZTc5NzU2MjM2NzAyNzRmYThiM2U2YzM4MWI1NTc1OWY=");

	private AppInfo ios = new AppInfo("1928", "ZTc5NzU2MjM2NzAyNzRmYThiM2U2YzM4MWI1NTc1OWY=");

	private static final Set<ChannelName> channel = Set.of(ChannelName.main);

	public static LaunchInterAdConfig interAdConfig;

	@Override
	public void afterPropertiesSet() throws Exception {
		interAdConfig = this;
	}

	public String getAppId(Client client) {
		AppInfo app = getApp(client);
		return app != null ? app.getAppId() : null;
	}

	public AppInfo getApp(Client client) {
		return client == Client.APP_IOS ? ios : android;
	}

	public static JSONObject request(Client client, String url, String traceToken, TreeMap<String, String> par) {
		final AppInfo appInfo = interAdConfig.getApp(client);
		if (appInfo != null && (Env.inTest() || Env.outer())) {
			final String value = String.valueOf(System.currentTimeMillis() / 1000);
			par.put("timestamp", value);
			par.put("event_time", value);
			par.put("app_id", appInfo.appId);
//			par.put("track_code", traceToken);
			String parStr = null;
			String res = null;
			final StopWatch stopWatch = new StopWatch();
			stopWatch.start();
			url = interAdConfig.baseUrl + url;
			try {
				String str = Joiner.on("&").useForNull("").withKeyValueSeparator("=").join(par);
				parStr = str + "&sign=" + Encrypter.md5(str + appInfo.secret);
				res = HttpUtil.doPost(url, parStr, null);
			} catch (RuntimeException ex) {
				log.error("广告系统报错", ex);
			} finally {
				stopWatch.stop();
				log.info("[广告系统] 耗时={}, 请求地址={}, 请求数据={}, 返回数据={}", stopWatch.getTotalTimeMillis(), url, parStr, res);
			}
			if (StringUtil.notEmpty(res)) {
				return JSONObject.parseObject(res);
			}
		}
		return new JSONObject();
	}

	@Getter
	@Setter
	@AllArgsConstructor
	@NoArgsConstructor
	public static class AppInfo {

		private String appId;
		private String secret;

	}

}
